<template>
  <div class="attendance-stats">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.stats') }}</span>
        <div :class="{'header-actions': true, 'mobile-header-actions': isMobile}">
          <el-tooltip :content="$t('attendance.exportStatsData')" placement="top">
            <el-button 
              type="primary" 
              size="small" 
              @click="exportStats" 
              :loading="exporting"
              class="export-button">
              <i class="el-icon-download"></i> <span class="button-text">{{ $t('attendance.exportStats') }}</span>
            </el-button>
          </el-tooltip>
        </div>
      </div>
      
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <!-- 班级/课程统计 -->
          <template v-if="viewType === 'groupCourse'">
            <el-form-item :label="$t('group.name')">
              <el-select v-model="searchForm.groupId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('group.name')" clearable>
                <el-option 
                  v-for="group in groups" 
                  :key="group.id" 
                  :label="group.name" 
                  :value="group.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('attendance.courseName')">
              <el-select v-model="searchForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.courseName')" clearable>
                <el-option 
                  v-for="course in courses" 
                  :key="course.id" 
                  :label="course.name" 
                  :value="course.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          
          <el-form-item :label="$t('common.dateRange')">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              :range-separator="$t('common.to')"
              :start-placeholder="$t('common.startDate')"
              :end-placeholder="$t('common.endDate')"
              value-format="yyyy-MM-dd"
              @change="handleDateRangeChange">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchStats">{{ $t('common.search') }}</el-button>
            <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 统计卡片 -->
      <div class="stats-cards" v-loading="loading">
        <!-- 全校统计 -->
        <template v-if="viewType === 'school' && schoolStats">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.totalAttendance') }}</div>
                <div class="stats-card-value">{{ schoolStats.total }}</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.normal') }}</div>
                <div class="stats-card-value">{{ schoolStats.normal }}</div>
                <div class="stats-card-rate">{{ schoolStats.normalRate }}%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.late') }}</div>
                <div class="stats-card-value">{{ schoolStats.late }}</div>
                <div class="stats-card-rate">{{ schoolStats.lateRate }}%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.absent') }}</div>
                <div class="stats-card-value">{{ schoolStats.absent }}</div>
                <div class="stats-card-rate">{{ schoolStats.absentRate }}%</div>
              </el-card>
            </el-col>
          </el-row>
        </template>
        
        <!-- 班级或课程统计 -->
        <template v-if="(viewType === 'groupCourse') && groupOrCourseStats">
          <div class="stat-header">{{ groupOrCourseStats.name }} {{ $t('attendance.statsOverview') }}</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.totalAttendance') }}</div>
                <div class="stats-card-value">{{ groupOrCourseStats.total }}</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.normal') }}</div>
                <div class="stats-card-value">{{ groupOrCourseStats.normal }}</div>
                <div class="stats-card-rate">{{ groupOrCourseStats.attendanceRate.toFixed(1) }}%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.late') }}</div>
                <div class="stats-card-value">{{ groupOrCourseStats.late }}</div>
                <div class="stats-card-rate">{{ groupOrCourseStats.total > 0 ? (groupOrCourseStats.late / groupOrCourseStats.total * 100).toFixed(1) : '0.0' }}%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.absent') }}</div>
                <div class="stats-card-value">{{ groupOrCourseStats.absent }}</div>
                <div class="stats-card-rate">{{ groupOrCourseStats.total > 0 ? (groupOrCourseStats.absent / groupOrCourseStats.total * 100).toFixed(1) : '0.0' }}%</div>
              </el-card>
            </el-col>
          </el-row>
        </template>
        
        <!-- 个人统计 -->
        <template v-if="viewType === 'personal' && personalStats">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.totalAttendance') }}</div>
                <div class="stats-card-value">{{ personalStats.total }}</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.normal') }}</div>
                <div class="stats-card-value">{{ personalStats.normal }}</div>
                <div class="stats-card-rate">{{ personalStats.normalRate }}%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.late') }}</div>
                <div class="stats-card-value">{{ personalStats.late }}</div>
                <div class="stats-card-rate">{{ personalStats.lateRate }}%</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover" class="stats-card">
                <div class="stats-card-title">{{ $t('attendance.absent') }}</div>
                <div class="stats-card-value">{{ personalStats.absent }}</div>
                <div class="stats-card-rate">{{ personalStats.absentRate }}%</div>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </div>
      
      <!-- 图表展示 -->
      <div class="chart-container" v-loading="loading">
        <div id="attendanceChart" class="chart"></div>
      </div>
      
      <!-- 数据表格 -->
      <div class="table-container" v-loading="loading" v-if="viewType === 'groupCourse'">
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column prop="date" :label="$t('common.date')" width="120"></el-table-column>
          <el-table-column prop="total" :label="$t('attendance.totalAttendance')" width="100"></el-table-column>
          <el-table-column prop="normal" :label="$t('attendance.normal')" width="100"></el-table-column>
          <el-table-column prop="late" :label="$t('attendance.late')" width="100"></el-table-column>
          <el-table-column prop="early" :label="$t('attendance.earlyLeave')" width="100"></el-table-column>
          <el-table-column prop="absent" :label="$t('attendance.absent')" width="100"></el-table-column>
          <el-table-column :label="$t('attendance.attendanceRate')" width="120">
            <template slot-scope="scope">
              {{ scope.row.attendanceRate ? scope.row.attendanceRate.toFixed(1) : (scope.row.total > 0 ? (scope.row.normal / scope.row.total * 100).toFixed(1) : '0.0') }}%
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { mapState } from 'vuex';
import { exportFile } from '@/utils/exportHelper';

export default {
  name: "AttendanceStats",
  data() {
    return {
      viewType: 'personal', // 默认个人统计
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      isTeacher: false,
      isAdmin: false,
      isStudent: false,
      loading: false,
      exporting: false, // 导出状态
      isMobile: false, // 移动端标记
      screenWidth: document.body.clientWidth,
      
      // 搜索表单
      searchForm: {
        groupId: null,
        courseId: null,
        startDate: null,
        endDate: null,
        studentId: null
      },
      dateRange: [],
      
      // 数据列表
      groups: [],
      courses: [],
      studentCourses: [],
      
      // 统计数据
      schoolStats: null,
      personalStats: null,
      groupOrCourseStats: null, // 班级或课程统计数据
      tableData: [],
      
      // 图表实例
      chart: null
    }
  },
  created() {
    this.checkUserRole();
    this.initData();
    this.checkScreenSize();
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
    window.addEventListener('resize', this.checkScreenSize);
    this.checkScreenSize();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.resizeChart);
    window.removeEventListener('resize', this.checkScreenSize);
  },
  computed: {
    ...mapState(['userId'])
  },
  methods: {
    // 检查屏幕尺寸并设置相应的布局
    checkScreenSize() {
      this.screenWidth = document.body.clientWidth;
      this.isMobile = this.screenWidth < 768;
    },
    
    checkUserRole() {
      // 检查用户角色
      if (this.userInfo && this.userInfo.roleName) {
        this.isTeacher = this.userInfo.roleName.includes('teacher');
        this.isAdmin = this.userInfo.roleName.includes('admin');
        this.isStudent = this.userInfo.roleName.includes('student');
        
        // 设置默认视图类型
        if (this.isAdmin) {
          this.viewType = 'school';
        } else if (this.isTeacher) {
          this.viewType = 'groupCourse';
        } else if (this.isStudent) {
          this.viewType = 'personal';
        }
      }
      
      // 设置默认学生ID
      this.searchForm.studentId = this.userInfo.userId;
    },
    initData() {
      // 获取班级列表
      if (this.isTeacher || this.isAdmin) {
        this.getGroups();
        this.getCourses();
      }
      
      // 获取学生课程
      if (!this.isTeacher && !this.isAdmin) {
        this.getStudentCourses();
      }
      
      // 获取统计数据
    //   this.searchStats();
    },
    getGroups() {
      this.$axios.get(`/group/teacher-groups/${this.userId}`).then(res => {
        if (res.code === 200) {
          this.groups = res.data || [];
        }
      }).catch(err => {
        console.error('获取班级列表失败', err);
        this.$message.error(this.$t('group.getClassFailed'));
      });
    },
    getCourses() {
      const params = {
        current: 1,
        size: 100,
        teacherId: this.userInfo.userId
      };
      this.$axios.get('/course/page', { params }).then(res => {
        if (res.code === 200) {
          this.courses = res.data.records || [];
        }
      }).catch(err => {
        console.error('获取课程列表失败', err);
        this.$message.error(this.$t('attendance.checkAdmin.getCourseFailed'));
      });
    },
    getStudentCourses() {
      const userId = this.userInfo.userId;
      this.$axios.get(`/course/student/${userId}`).then(res => {
        if (res.code === 200) {
          this.studentCourses = res.data || [];
        }
      }).catch(err => {
        console.error('获取学生课程失败', err);
        this.$message.error(this.$t('course.getCoursesError'));
      });
    },
    handleDateRangeChange(val) {
      if (val) {
        this.searchForm.startDate = val[0];
        this.searchForm.endDate = val[1];
      } else {
        this.searchForm.startDate = null;
        this.searchForm.endDate = null;
      }
    },
    searchStats() {
      this.loading = true;
      
      // 根据视图类型选择API和参数
      let url = '';
      let params = {};
      
      switch (this.viewType) {
        case 'groupCourse':
          // 如果同时选择了班级和课程，使用课程统计接口
          if (this.searchForm.courseId) {
            url = `/statistics/attendance/course/${this.searchForm.courseId}`;
          } 
          // 如果只选择了班级，使用班级统计接口
          else if (this.searchForm.groupId) {
            url = `/statistics/attendance/group/${this.searchForm.groupId}`;
          } else {
            this.$message.warning(this.$t('common.pleaseSelect') + ' ' + this.$t('group.title') + '/' + this.$t('course.title'));
            this.loading = false;
            return;
          }
          break;
        case 'personal':
          url = `/statistics/attendance/user/${this.searchForm.studentId}`;
          // 如果选择了课程，添加课程ID参数
          if (this.searchForm.courseId) {
            params.courseId = this.searchForm.courseId;
          }
          break;
        case 'school':
          // 全校统计使用图表数据接口
          url = '/statistics/attendance/chart';
          break;
      }
      
      // 添加日期范围
      if (this.searchForm.startDate && this.searchForm.endDate) {
        params.startDate = this.searchForm.startDate;
        params.endDate = this.searchForm.endDate;
      }
      
      this.$axios.get(url, { params }).then(res => {
        if (res.code === 200) {
          const data = res.data;
          
          switch (this.viewType) {
            case 'groupCourse':
              this.processGroupOrCourseStats(data);
              break;
            case 'personal':
              this.processPersonalStats(data);
              break;
            case 'school':
              this.schoolStats = this.processSchoolStats(data);
              break;
          }
          
          // 更新图表
          this.updateChart();
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.getStatsDataFailed'));
        }
      }).catch(err => {
        console.error('获取统计数据失败', err);
        this.$message.error(this.$t('attendance.getStatsDataFailed'));
      }).finally(() => {
        this.loading = false;
      });
    },
    processGroupOrCourseStats(data) {
      // 获取详细列表数据
      const listUrl = this.viewType === 'groupCourse' 
        ? `/statistics/attendance/group/${this.searchForm.groupId}/list` 
        : `/statistics/attendance/course/${this.searchForm.courseId}/list`;
      
      // 根据接口文档处理单个统计对象
      if (data) {
        this.groupOrCourseStats = {
          id: data.id || 0,
          name: data.name || '',
          total: data.totalCount || 0,
          normal: data.normalCount || 0,
          late: data.lateCount || 0,
          early: data.earlyLeaveCount || 0,
          absent: data.absentCount || 0,
          leave: data.leaveCount || 0,
          attendanceRate: data.attendanceRate || 0
        };
      }
      
      // 获取列表数据
      this.$axios.get(listUrl).then(res => {
        if (res.code === 200) {
          // 确保数据格式统一
          this.tableData = (res.data || []).map(item => ({
            date: item.date || '',
            name: item.name || '',
            id: item.id || 0,
            total: item.totalCount || 0,
            normal: item.normalCount || 0,
            late: item.lateCount || 0,
            early: item.earlyLeaveCount || 0,
            absent: item.absentCount || 0,
            leave: item.leaveCount || 0,
            attendanceRate: item.attendanceRate
          }));
        }
      }).catch(err => {
        console.error('获取统计列表失败', err);
      });
    },
    processPersonalStats(data) {
      // 根据接口文档 AttendanceStatsDTO 更新字段映射
      this.personalStats = {
        total: data.totalCount || 0,
        normal: data.normalCount || 0,
        late: data.lateCount || 0,
        early: data.earlyLeaveCount || 0,
        absent: data.absentCount || 0,
        leave: data.leaveCount || 0,
        // 计算百分比，如果后端没有提供
        normalRate: data.attendanceRate || (data.totalCount > 0 ? (data.normalCount / data.totalCount * 100).toFixed(1) : 0),
        lateRate: data.lateRate || (data.totalCount > 0 ? (data.lateCount / data.totalCount * 100).toFixed(1) : 0),
        earlyRate: data.earlyLeaveRate || (data.totalCount > 0 ? (data.earlyLeaveCount / data.totalCount * 100).toFixed(1) : 0),
        absentRate: data.absentRate || (data.totalCount > 0 ? (data.absentCount / data.totalCount * 100).toFixed(1) : 0),
        leaveRate: data.leaveRate || (data.totalCount > 0 ? (data.leaveCount / data.totalCount * 100).toFixed(1) : 0)
      };
      
      //console.log('处理后的个人统计数据:', this.personalStats);
    },
    processSchoolStats(data) {
        //console.log(data);
      // 根据接口返回的数据格式处理全校统计数据
      // 新格式: data包含：statusCounts (对象，每个状态对应一个数组), dates (日期数组)
      
      // 计算各状态的总数
      const normalCount = data.statusCounts?.normal ? data.statusCounts.normal.reduce((sum, count) => sum + count, 0) : 0;
      const lateCount = data.statusCounts?.late ? data.statusCounts.late.reduce((sum, count) => sum + count, 0) : 0;
      const earlyCount = data.statusCounts?.earlyLeave ? data.statusCounts.earlyLeave.reduce((sum, count) => sum + count, 0) : 0;
      const absentCount = data.statusCounts?.absent ? data.statusCounts.absent.reduce((sum, count) => sum + count, 0) : 0;
      const leaveCount = data.statusCounts?.leave ? data.statusCounts.leave.reduce((sum, count) => sum + count, 0) : 0;
      
      // 计算总考勤数
      const total = normalCount + lateCount + earlyCount + absentCount + leaveCount;
      
      // 计算各状态的比率
      const normalRate = total > 0 ? (normalCount / total * 100).toFixed(1) : 0;
      const lateRate = total > 0 ? (lateCount / total * 100).toFixed(1) : 0;
      const earlyRate = total > 0 ? (earlyCount / total * 100).toFixed(1) : 0;
      const absentRate = total > 0 ? (absentCount / total * 100).toFixed(1) : 0;
      const leaveRate = total > 0 ? (leaveCount / total * 100).toFixed(1) : 0;
      
      return {
        total: total,
        normal: normalCount,
        late: lateCount,
        early: earlyCount,
        absent: absentCount,
        leave: leaveCount,
        normalRate: normalRate,
        lateRate: lateRate,
        earlyRate: earlyRate,
        absentRate: absentRate,
        leaveRate: leaveRate
      };
    },
    updateChart() {
      if (!this.chart) {
        this.initChart();
        return;
      }
      
      let option = {};
      
      // 根据视图类型构建不同的图表选项
      if (this.viewType === 'school') {
        // 使用接口返回的数据获取全校统计图表数据
        let params = {};
        // 添加日期范围参数
        if (this.searchForm.startDate && this.searchForm.endDate) {
          params.startDate = this.searchForm.startDate;
          params.endDate = this.searchForm.endDate;
        }
        
        this.$axios.get('/statistics/attendance/chart', { params }).then(res => {
          if (res.code === 200) {
            const chartData = res.data;
            
            // 处理状态分布数据作为饼图数据
            let pieData = [];
            if (chartData.statusCounts) {
              // 计算各状态的总和
              const normalCount = chartData.statusCounts.normal ? chartData.statusCounts.normal.reduce((sum, count) => sum + count, 0) : 0;
              const lateCount = chartData.statusCounts.late ? chartData.statusCounts.late.reduce((sum, count) => sum + count, 0) : 0;
              const earlyCount = chartData.statusCounts.earlyLeave ? chartData.statusCounts.earlyLeave.reduce((sum, count) => sum + count, 0) : 0;
              const absentCount = chartData.statusCounts.absent ? chartData.statusCounts.absent.reduce((sum, count) => sum + count, 0) : 0;
              const leaveCount = chartData.statusCounts.leave ? chartData.statusCounts.leave.reduce((sum, count) => sum + count, 0) : 0;

              // 构建饼图数据
              pieData = [
                { name: this.$t('attendance.normal'), value: normalCount, itemStyle: { color: '#67C23A' } },
                { name: this.$t('attendance.late'), value: lateCount, itemStyle: { color: '#E6A23C' } },
                { name: this.$t('attendance.earlyLeave'), value: earlyCount, itemStyle: { color: '#909399' } },
                { name: this.$t('attendance.absent'), value: absentCount, itemStyle: { color: '#F56C6C' } },
                { name: this.$t('attendance.leave'), value: leaveCount, itemStyle: { color: '#409EFF' } }
              ];
            }
            
            // 从数据中提取图例数据
            const legendData = pieData.map(item => item.name);
            
            // 使用与其他统计相同的饼图样式
            option = {
              title: {
                text: this.$t('attendance.schoolRecords'),
                left: 'center'
              },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                orient: 'horizontal',
                bottom: 10,
                data: legendData
              },
              series: [
                {
                  name: this.$t('attendance.stats'),
                  type: 'pie',
                  radius: ['40%', '70%'],
                  avoidLabelOverlap: false,
                  itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                  },
                  label: {
                    show: false,
                    position: 'center'
                  },
                  emphasis: {
                    label: {
                      show: true,
                      fontSize: '18',
                      fontWeight: 'bold'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: pieData
                }
              ]
            };
            
            this.chart.setOption(option);
          }
        }).catch(err => {
          console.error('获取图表数据失败', err);
        });
      } else {
        // 个人统计和其他统计使用饼图
        const chartData = this.getChartData();
        
        // 从实际数据中提取图例数据
        const legendData = chartData.map(item => item.name);
        
        option = {
          title: {
            text: this.getChartTitle(),
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'horizontal',
            bottom: 10,
            data: legendData
          },
          series: [
            {
              name: '考勤统计',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: chartData
            }
          ]
        };
        
        this.chart.setOption(option);
      }
    },
    getChartTitle() {
      switch (this.viewType) {
        case 'groupCourse':
          const group = this.groups.find(g => g.id === this.searchForm.groupId);
          const course = this.courses.find(c => c.id === this.searchForm.courseId);
          return group ? `${group.name}${this.$t('attendance.statsOverview')}` : course ? `${course.name}${this.$t('attendance.statsOverview')}` : this.$t('attendance.classOrCourseStats');
        case 'personal':
          return this.$t('attendance.personalAttendance');
        case 'school':
          return this.$t('attendance.schoolRecords');
        default:
          return this.$t('attendance.stats');
      }
    },
    getChartData() {
      let stats;
      
      switch (this.viewType) {
        case 'personal':
          stats = this.personalStats;
          break;
        case 'school':
          stats = this.schoolStats;
          break;
        case 'groupCourse':
          stats = this.groupOrCourseStats;
          break;
        default:
          return [];
      }
      
      if (!stats) return [];
      
      return [
        { value: stats.normal, name: this.$t('attendance.normal'), itemStyle: { color: '#67C23A' } },
        { value: stats.late, name: this.$t('attendance.late'), itemStyle: { color: '#E6A23C' } },
        { value: stats.early, name: this.$t('attendance.earlyLeave'), itemStyle: { color: '#909399' } },
        { value: stats.absent, name: this.$t('attendance.absent'), itemStyle: { color: '#F56C6C' } },
        { value: stats.leave, name: this.$t('attendance.leave'), itemStyle: { color: '#409EFF' } }
      ];
    },
    resetSearch() {
      this.searchForm = {
        groupId: null,
        courseId: null,
        startDate: null,
        endDate: null,
        studentId: this.userInfo.userId
      };
      this.dateRange = [];
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('attendanceChart'));
      window.addEventListener('resize', () => {
        this.chart.resize();
      });
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    // 导出统计数据
    exportStats() {
      this.exporting = true;
      
      // 构建查询参数
      let params = {};
      let url = '';
      
      // 根据当前视图类型和搜索条件构建参数
      switch (this.viewType) {
        case 'groupCourse':
          // 导出班级或课程考勤统计
          if (this.searchForm.courseId) {
            // 课程考勤统计
            url = `/attendance/export/course/${this.searchForm.courseId}`;
          } else if (this.searchForm.groupId) {
            // 班级考勤统计
            url = `/attendance/export/group/${this.searchForm.groupId}`;
          } else {
            this.$message.warning(this.$t('common.pleaseSelect') + ' ' + this.$t('group.title') + '/' + this.$t('course.title'));
            this.exporting = false;
            return;
          }
          break;
        case 'personal':
          // 导出个人考勤统计
          url = `/attendance/export/user/${this.searchForm.studentId}`;
          if (this.searchForm.courseId) {
            params.courseId = this.searchForm.courseId;
          }
          break;
        case 'school':
          // 全校考勤统计
          url = '/attendance/export';
          break;
      }
      
      // 添加时间范围参数
      if (this.searchForm.startDate && this.searchForm.endDate) {
        params.startDate = this.searchForm.startDate;
        params.endDate = this.searchForm.endDate;
      }
      
      exportFile({
        url,
        params,
        defaultFileName: '考勤统计',
        beforeExport: () => {
          // 导出前的操作已在函数开始时执行，这里不需要再设置
        },
        afterExport: () => {
          this.exporting = false;
        },
        fileType: 'csv',
        getCustomFileName: () => {
          // 根据当前视图类型生成文件名
          const now = new Date();
          const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
          let fileName = `${this.$t('attendance.stats')}_${dateStr}`;
          
          switch (this.viewType) {
            case 'groupCourse':
              if (this.searchForm.groupId && this.groups.length > 0) {
                const group = this.groups.find(g => g.id === this.searchForm.groupId);
                if (group) {
                  fileName = `${group.name}_${this.$t('attendance.stats')}_${dateStr}`;
                }
              } else if (this.searchForm.courseId && this.courses.length > 0) {
                const course = this.courses.find(c => c.id === this.searchForm.courseId);
                if (course) {
                  fileName = `${course.name}_${this.$t('attendance.stats')}_${dateStr}`;
                }
              }
              break;
            case 'personal':
              fileName = `${this.$t('attendance.personalAttendance')}_${dateStr}`;
              if (this.searchForm.courseId && this.studentCourses.length > 0) {
                const course = this.studentCourses.find(c => c.id === this.searchForm.courseId);
                if (course) {
                  fileName += `_${course.name}`;
                }
              }
              break;
            case 'school':
              fileName = `${this.$t('attendance.schoolRecords')}_${dateStr}`;
              break;
          }
          
          // 添加日期范围到文件名
          if (this.searchForm.startDate && this.searchForm.endDate) {
            fileName += `_${this.searchForm.startDate}${this.$t('common.to')}${this.searchForm.endDate}`;
          }
          
          return fileName;
        }
      });
    }
  }
}
</script>

<style scoped>
.attendance-stats {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.stats-cards {
  margin-top: 20px;
  margin-bottom: 30px;
}

.stat-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #409EFF;
}

.stats-card {
  text-align: center;
}

.stats-card-title {
  font-size: 14px;
  color: #606266;
}

.stats-card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.stats-card-rate {
  font-size: 14px;
  color: #409EFF;
}

.chart-container {
  margin-top: 20px;
  margin-bottom: 30px;
}

.chart {
  width: 100%;
  height: 400px;
}

.table-container {
  margin-top: 20px;
}

/* 头部操作区样式 */
.header-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  float: right;
}

.mobile-header-actions {
  flex-direction: column;
  align-items: flex-end;
  float: none;
  margin-top: 10px;
}

.mobile-header-actions .export-button {
  width: 100%;
}

@media screen and (max-width: 768px) {
  .clearfix {
    display: flex;
    flex-direction: column;
  }
  
  .button-text {
    display: inline-block;
  }
  
  .export-button {
    margin-left: 0 !important;
    margin-top: 8px;
    width: 100%;
  }

  .search-container .el-form-item {
    display: block;
    width: 100%;
    margin-right: 0;
  }

  .search-container .el-select, 
  .search-container .el-date-editor {
    width: 100%;
  }

  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 15px;
  }
}
</style> 